package com.caoxw.Android.CityBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class Update extends Thread {
	private Context m_context = null;
	private Handler m_handler = null;
	
	public int version = 0;
	private String	m_strAppUrl = "";
	private boolean suspend = false;
	public final static int MSG_FLAG_DOWNLOAD_APP_ERROR			=  100;
	public final static int MSG_FLAG_DOWNLOAD_APP_START 		=  101;
	public final static int MSG_FLAG_DOWNLOAD_APP_PROCESS 		=  102;
	public final static int MSG_FLAG_DOWNLOAD_APP_FINISHED 		=  103;
	public final static int MSG_FLAG_VERSION_APP_AVAILABLE 		=  104;
	
	public final static int MSG_FLAG_DOWNLOAD_DATA_ERROR		=  110;
	public final static int MSG_FLAG_DOWNLOAD_DATA_START 		=  111;
	public final static int MSG_FLAG_DOWNLOAD_DATA_PROCESS 		=  112;
	public final static int MSG_FLAG_DOWNLOAD_DATA_FINISHED 	=  113;
	
	public void continueRun(){
		suspend = false;
		
	}
	public Update(Context context){
		m_context = context;
	}
	
	public Update(Context context,Handler handler){
		m_context = context;
		m_handler = handler;
		
	}
	@SuppressWarnings("static-access")
	public void run(){
		if(checkNewVersion()){
			suspend = true;
		try {
			while(suspend)
				this.sleep(300);
		} catch (InterruptedException e) {
			return;
			}

			sendMsg(MSG_FLAG_DOWNLOAD_APP_START);
			Log.d("Update Thread","Resume");
			DownDataFile(m_strAppUrl,"LatestCityBus.apk");
		}
	}
	
	public boolean checkNewVersion(){
		HttpUtil objHttp = new HttpUtil();
		String strResult = objHttp.HttpGet("/Version");
		System.out.println(strResult);
		if(!objHttp.isError){
			try {
				JSONObject objJson;
				objJson = new JSONObject(strResult);
				int intVersion = objJson.getInt("version");
				m_strAppUrl = objJson.getString("url");
				int currentVersion = m_context.getPackageManager().getPackageInfo(m_context.getPackageName(), 0).versionCode;
				if(intVersion>currentVersion){
					sendMsg(MSG_FLAG_VERSION_APP_AVAILABLE,intVersion);
					return true;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}
	public void DownDataFile(String FilePath, String SavePath) {
		System.out.println(FilePath);
		try {
			URL myURL = new URL(FilePath);
			URLConnection conn = myURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();

			int fileSize = conn.getContentLength();// 根据响应获取文件大小
			if (fileSize <= 0){
				 sendMsg(MSG_FLAG_DOWNLOAD_APP_ERROR,0,0,"下载失败：\n无法获知文件大小");
				 return;
			}
				//throw new RuntimeException("无法获知文件大小 "+ FilePath);
			if (is == null){
				sendMsg(MSG_FLAG_DOWNLOAD_APP_ERROR,0,0,"下载失败：\n本地无法写入");
				 return;
			}
			File file = new File(Environment.getExternalStorageDirectory(), SavePath);
			//System.out.println(Environment.getExternalStorageDirectory());
			FileOutputStream fos = new FileOutputStream(file);//m_context.openFileOutput(SavePath, Context.MODE_WORLD_READABLE);
			//FileOutputStream fos = m_context.openFileOutput(SavePath, Context.MODE_WORLD_READABLE);
			byte buf[] = new byte[1024];
			int downLoadFileSize = 0;

			do {
				// 循环读取
				int numread = is.read(buf);
				if (numread == -1) {
					break;
				}
				fos.write(buf, 0, numread);
				downLoadFileSize += numread;
				sendMsg(MSG_FLAG_DOWNLOAD_APP_PROCESS,downLoadFileSize,fileSize,null);

			} while (true);
			fos.close();
			is.close();
			sendMsg(MSG_FLAG_DOWNLOAD_APP_FINISHED,0,0,Environment.getExternalStorageDirectory() + "/" + SavePath);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			sendMsg(MSG_FLAG_DOWNLOAD_APP_ERROR,0,0,"IO错误,请检查存储卡是否可写");
		}
	}


	
	protected void sendMsg(int flag,int arg1) {
		sendMsg(flag,arg1,0,null);
	}
	protected void sendMsg(int flag) {
		sendMsg(flag,0,0,null);
	}
	protected void sendMsg(int flag,int arg1,int arg2,Object object) {
		if(null==m_handler) return ;
		Message msg = new Message();
		msg.arg1 = arg1;
		msg.arg2 = arg2;
		msg.what = flag;
		msg.obj = object;
		m_handler.sendMessage(msg);
	}
	
	

}
